/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package beans;

import DAO.Evenement;
import DAO.Service;
import java.awt.Event;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.primefaces.component.schedule.Schedule;
import org.primefaces.event.ScheduleEntryMoveEvent;
import org.primefaces.event.ScheduleEntryResizeEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultScheduleEvent;
import org.primefaces.model.DefaultScheduleModel;
import org.primefaces.model.ScheduleEvent;
import org.primefaces.model.ScheduleModel;
import transformations.Update;
import util.CustumEvent;
import util.GestionFichier;

/*eventModel=new DefaultScheduleModel();
                
 event=ce;
 //event = new CustumEvent("rien",previousDay8Pm(), previousDay11Pm(),true);
 event.setId("pwa");
                
		
 eventModel.addEvent(event);*/

@ManagedBean(name = "scheduleController")
@ViewScoped
public class ScheduleController implements Serializable {
    
    private int id;
    private ScheduleModel eventModel;
    private ScheduleEvent event = new DefaultScheduleEvent();

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    
    public ScheduleController() {
        event = getCostumEvent(null);
        eventModel = new DefaultScheduleModel();
        
        try {
            
            loadEvt();
            
            
            //System.out.println("eventsModel:\n"+eventModel.getEvents().toString());
        } catch (IOException ex) {
            Logger.getLogger(ScheduleController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalStateException ex) {
            Logger.getLogger(ScheduleController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ServletException ex) {
            Logger.getLogger(ScheduleController.class.getName()).log(Level.SEVERE, null, ex);
        }
        /*
        eventModel.addEvent(event);
        eventModel.addEvent(new DefaultScheduleEvent("Champions League Match", previousDay8Pm(), previousDay11Pm()));
        eventModel.addEvent(new DefaultScheduleEvent("Birthday Party", today1Pm(), today6Pm()));
        eventModel.addEvent(new DefaultScheduleEvent("Breakfast at Tiffanys", nextDay9Am(), nextDay11Am()));
        eventModel.addEvent(new DefaultScheduleEvent("Plant the new garden stuff", theDayAfter3Pm(), fourDaysLater3pm()));
    */}

    private void loadEvt() throws IOException, IllegalStateException, ServletException {
        
        List<ScheduleEvent> events = new Vector<>();
        FacesContext ctx = FacesContext.getCurrentInstance();
        final HttpServletRequest req = (HttpServletRequest) ctx.getExternalContext().getRequest();        
        //String fichier = req.getParameter("j_idt8:scroll_input");
        
        String login=req.getParameter("j_idt9:j_idt15");
        String password=req.getParameter("j_idt9:j_idt17");
        Service service=new Service();
        
        this.id=service.getEtudiant(login, password);
        List<Evenement> evenements=service.getEvenementsEtudiant(service.getEtudiant(this.id));
        for(Evenement e:evenements){
            events.add(new DefaultScheduleEvent(e.getTitre(), e.getDatedebut(), e.getDatefin(),e.getLocalisation()));
        }
        for(ScheduleEvent e:events){
            eventModel.addEvent(e);
        }
        int id=service.getEtudiant(this.id).getIdparcours();
        String fichier=service.getParcour(id).getIntitule();
        GestionFichier gf=new GestionFichier();
        List<CustumEvent> evennements=gf.getAllEvents(fichier);
                
            int cpt=0;
            for(CustumEvent evt: evennements){
                cpt++;
                if(cpt==16)break;
                eventModel.addEvent(evt);
            }
        
    }

    private CustumEvent getCostumEvent(SelectEvent selectEvent) {

        CustumEvent ce = new CustumEvent();
        ce.setTitle(event.getTitle());
        ce.setAnneeDebut("2013");
        ce.setMoisDebut("12");
        ce.setJourDebut("25");
        ce.setAnneeFin("2013");
        ce.setMoisFin("12");
        ce.setJourFin("25");
        ce.setHeureDebut("08");
        ce.setMinuteDebut("00");
        ce.setHeureFin("10");
        ce.setMinuteFin("00");
        System.out.println("Je suis arrivé ici ");
        ce.setStartDate(ce.getDateDebut());
        ce.setEndDate(ce.getDateFin());
        ce.setAllDay(false);
        //event=new DefaultScheduleEvent();
        return ce;
    }

    public Date getRandomDate(Date base) {
        Calendar date = Calendar.getInstance();
        date.setTime(base);
        date.add(Calendar.DATE, ((int) (Math.random() * 30)) + 1);	//set random day of month

        return date.getTime();
    }
    /*public void removeEvent(ScheduleEvent event1){
     eventModel.deleteEvent(event);
     }*/

    public Date getInitialDate() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), Calendar.FEBRUARY, calendar.get(Calendar.DATE), 0, 0, 0);

        return calendar.getTime();
    }

    public ScheduleModel getEventModel() {
        return eventModel;
    }

    private Calendar today() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), 0, 0, 0);

        return calendar;
    }

    private Date previousDay8Pm() {
        Calendar t = (Calendar) today().clone();
        t.set(Calendar.AM_PM, Calendar.PM);
        t.set(Calendar.DATE, t.get(Calendar.DATE) - 1);
        t.set(Calendar.HOUR, 8);

        return t.getTime();
    }

    private Date previousDay11Pm() {
        Calendar t = (Calendar) today().clone();
        t.set(Calendar.AM_PM, Calendar.PM);
        t.set(Calendar.DATE, t.get(Calendar.DATE) - 1);
        t.set(Calendar.HOUR, 11);

        return t.getTime();
    }

    private Date today1Pm() {
        Calendar t = (Calendar) today().clone();
        t.set(Calendar.AM_PM, Calendar.PM);
        t.set(Calendar.HOUR, 1);

        return t.getTime();
    }

    private Date theDayAfter3Pm() {
        Calendar t = (Calendar) today().clone();
        t.set(Calendar.DATE, t.get(Calendar.DATE) + 2);
        t.set(Calendar.AM_PM, Calendar.PM);
        t.set(Calendar.HOUR, 3);

        return t.getTime();
    }

    private Date today6Pm() {
        Calendar t = (Calendar) today().clone();
        t.set(Calendar.AM_PM, Calendar.PM);
        t.set(Calendar.HOUR, 6);

        return t.getTime();
    }

    private Date nextDay9Am() {
        Calendar t = (Calendar) today().clone();
        t.set(Calendar.AM_PM, Calendar.AM);
        t.set(Calendar.DATE, t.get(Calendar.DATE) + 1);
        t.set(Calendar.HOUR, 9);

        return t.getTime();
    }

    private Date nextDay11Am() {
        Calendar t = (Calendar) today().clone();
        t.set(Calendar.AM_PM, Calendar.AM);
        t.set(Calendar.DATE, t.get(Calendar.DATE) + 1);
        t.set(Calendar.HOUR, 11);

        return t.getTime();
    }

    private Date fourDaysLater3pm() {
        Calendar t = (Calendar) today().clone();
        t.set(Calendar.AM_PM, Calendar.PM);
        t.set(Calendar.DATE, t.get(Calendar.DATE) + 4);
        t.set(Calendar.HOUR, 3);

        return t.getTime();
    }

    public ScheduleEvent getEvent() {
        return event;
    }

    public void setEvent(ScheduleEvent event) {
        this.event = event;
    }
    
    private Calendar getCalendarFromDate(Date date){
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(date);
        return calendar;
    }

    public void addEvent(ActionEvent actionEvent) {
        Evenement evenement=new Evenement();
            evenement.setTitre(event.getTitle());
            Date dateStart=event.getStartDate();
            Calendar calendar=getCalendarFromDate(dateStart);
            evenement.setHeuredebut(calendar.get(Calendar.HOUR));
            evenement.setMinutedebut(calendar.get(Calendar.MINUTE));
            calendar=getCalendarFromDate(event.getEndDate());
            evenement.setHeurefin(calendar.get(Calendar.HOUR));
            evenement.setMinutefin(calendar.get(Calendar.MINUTE));
            evenement.setDatedebut(dateStart);
            evenement.setDatefin(event.getEndDate());
            evenement.setIdetudiant(id);
            Service service=new Service();
        if (event.getId() == null) {
            //System.out.println("id ScheduleController: "+id);  
            
            service.addEvenement(evenement);
            eventModel.addEvent(event);
            
        } else {
            service.updateEvenement(evenement);
            eventModel.updateEvent(event);
        }

        event = new DefaultScheduleEvent();
    }

    public void onEventSelect(SelectEvent selectEvent) {
        event = (ScheduleEvent) selectEvent.getObject();
    }

    public void onDateSelect(SelectEvent selectEvent) {
        event = new DefaultScheduleEvent("", (Date) selectEvent.getObject(), (Date) selectEvent.getObject());
    }

    public void onEventMove(ScheduleEntryMoveEvent event) {
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Evénement mis à jour", "décalage de date:" + event.getDayDelta() + ", décalage de minutes:" + event.getMinuteDelta());

        addMessage(message);
    }

    public void onEventResize(ScheduleEntryResizeEvent event) {
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Evénement mis à jour", "décalage de date:" + event.getDayDelta() + ", décalage de minutes:" + event.getMinuteDelta());

        addMessage(message);
    }

    private void addMessage(FacesMessage message) {
        FacesContext.getCurrentInstance().addMessage(null, message);
    }

    public void supprimer() {
        Evenement evenement=new Evenement();
            evenement.setTitre(event.getTitle());
            Date dateStart=event.getStartDate();
            Calendar calendar=getCalendarFromDate(dateStart);
            evenement.setHeuredebut(calendar.get(Calendar.HOUR));
            evenement.setMinutedebut(calendar.get(Calendar.MINUTE));
            
            evenement.setDatedebut(new java.sql.Date(calendar.get(Calendar.YEAR)-1900,calendar.get(Calendar.MONTH),calendar.get(Calendar.DATE)));
            calendar=getCalendarFromDate(event.getEndDate());
            evenement.setHeurefin(calendar.get(Calendar.HOUR));
            evenement.setMinutefin(calendar.get(Calendar.MINUTE));
            
            evenement.setDatefin(new java.sql.Date(calendar.get(Calendar.YEAR)-1900,calendar.get(Calendar.MONTH),calendar.get(Calendar.DATE)));
        
            
        System.out.println("Date evt:"+ evenement.getDatefin());
            
        Service service=new Service();
        service.removeEvenement(evenement);
        eventModel.deleteEvent(event);
    }
}
